#include <iostream>
#include <string>
#include <unistd.h>
#include <cstring>
#include <cstdlib>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

void Usage(char *argv)
{
    std::cout << "Usage: " << argv << " ip:   port: " << std::endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }

    // 链接
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    inet_pton(AF_INET, serverip.c_str(), &(server.sin_addr));
    socklen_t len = sizeof(server);

    int sockfd = 0;
    while (1)
    {
        // 重连
        int cnt = 5;
        bool isreconnect = false;
        // 创建套接字
        sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd < 0)
        {
            std::cerr << "create socket failed, errno: " << errno << " ,err string: " << strerror(errno) << std::endl;
            exit(2);
        }
        //std::cout << "create socket success" << std::endl;
        // 是否需要绑定?显示绑定？需要绑定，但不需要显示绑定，操作系统来绑定，为我们选取端口号

        do
        {
            //请求链接
            int n = connect(sockfd, (struct sockaddr *)&server, len);
            if (n < 0)
            {
                isreconnect = true;
                cnt--;
                std::cerr << "connect failed, reconnect :" << cnt << std::endl;
                sleep(1);
            }
            else
            {
                break;
            }
        } while (cnt && isreconnect);

        if(cnt == 0)
        {
            std::cerr << "use offline" << std::endl;
            break;
        }

        std::string message;
        // while(1)
        // {
        std::cout << "Please Enter# ";
        getline(std::cin, message);
        // 发送信息
        int n = write(sockfd, message.c_str(), message.size());
        if (n < 0)
        {
            std::cout << "write error" << std::endl;
            // break;
        }

        char inbuffer[4096];
        n = read(sockfd, inbuffer, sizeof(inbuffer));
        if (n > 0)
        {
            inbuffer[n] = 0;
            std::cout << inbuffer << std::endl;
        }
        // }
        close(sockfd);
    }

    return 0;
}
